package com.wh1200.mybatis.xmlless.model

import com.wh1200.mybatis.xmlless.enums.JoinType
import com.wh1200.mybatis.xmlless.model.exception.BuildSQLException
import net.sf.jsqlparser.expression.Expression

/**
 *
 * Created by 吴昊 on 2018-12-06.
 *
 * @author 吴昊
 * @since 0.0.1
 * @param joinTable 连接的表名称
 * @param type 连接类型： LEFT,RIGHT,INNER
 * @param joinExpression 主表对应的持久化类中用于连接的属性名称
 * @param targetExpression 连接表中用于连接的数据库字段名称
 */
abstract class JoinInfo(
    val joinTable: TableName,
    val type: JoinType,
    private val joinExpression: Expression,
    val targetExpression: Expression,
    val typeInfo: TypeInfo,
    val joinTableInfo: XmllessTableInfo?,
) {

  /**
   * 返回用于关联表的属性名称
   * 如果属性为空，则默认使用主键属性
   */
  open fun getJoinProperty(tableInfo: XmllessTableInfo): String {
    return when {
      joinExpression.toString().isEmpty() -> tableInfo.keyProperty
        ?: throw BuildSQLException("无法解析${tableInfo.entityTypeName}的主键属性")

      else                                -> joinExpression.toString()
    }
  }

  abstract fun selectFields(level: Int, prefix: String? = null, tablePrefix: String? = null): List<SelectColumn>

  override fun toString(): String {
    return "$type JOIN $joinTable ON $joinExpression = $targetExpression"
  }

}
